package com.jinhao.crowd.mvc.handler;

import com.github.pagehelper.PageInfo;
import com.jinhao.crowd.entity.Role;
import com.jinhao.crowd.service.api.RoleService;
import com.jinhao.crowd.util.CrowdConstant;
import com.jinhao.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created on 2020/10/20.
 *
 * @author Valar Morghulis
 */
@Controller
public class RoleHandler {

    @Autowired
    private RoleService roleService;


    /**
     * 模态框确认删除的响应函数，融合多条和单条删除
     */
    @ResponseBody
    @RequestMapping("/role/remove/roleIdArray.json")
    public ResultEntity<String> removeRole(@RequestBody Integer[] roleIdArray) {
        roleService.removeRoleById(roleIdArray);
        return ResultEntity.successWithoutData();
    }

    /**
     * 模态框更新按钮的响应函数，对角色进行更新
     */
    @ResponseBody
    @RequestMapping("/role/update.json")
    public ResultEntity<String> updateRole(Role role) {
        roleService.updateRole(role);
        return ResultEntity.successWithoutData();
    }

    /**
     * 根据关键字获取角色列表并分页
     */
    @PreAuthorize("hasRole('经理')")
    @ResponseBody
    @RequestMapping("/role/get/page/info.json")
    public ResultEntity<PageInfo<Role>> getRolePageInfo(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                        @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                        @RequestParam(value = "keyword", defaultValue = "") String keyword) {
        PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum, pageSize, keyword);
        return ResultEntity.successWithData(pageInfo);
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @ResponseBody
    @RequestMapping("/role/save.json")
    public ResultEntity<String> addRole(Role role) {

        roleService.saveRole(role);

        return ResultEntity.successWithoutData();
    }
}
